package com.tsxy.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tsxy.entity.User;
import com.tsxy.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtil {

   private static IUserService staticUserService;

    @Resource
    private IUserService userService;

    @PostConstruct
    public void setStaticUserService(){
        staticUserService = userService;
    }

    public static String genToken(Integer userId,String sign){
        return JWT.create().withAudience(String.valueOf(userId))// 将userId作为载荷保存到Token中
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))
                .sign(Algorithm.HMAC256(sign)); //以password作为token的秘钥
    }

    public static User getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if ( StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                User us = staticUserService.getById(userId);
                return us;
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}
